<?php

namespace app\system\controller;

use app\system\model\SysMenuModel;
use think\Request;

class MenuList extends MainFrame
{
    public function showList(SysMenuModel $sysMenuModel, Request $request)
    {
        $menuList = $sysMenuModel->getMenuList();
        $menuList = $this->buildTree($menuList);    // 构建树形结构
        // dump($menuList);die;
        $this->assign("menuList", $menuList);
        return $this->fetch();
    }

    public function menuAdd(Request $request, SysMenuModel $sysMenuModel)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            $addResult = $sysMenuModel->addMenuData($data);
            if ($addResult != false) {
                return json(["code" => 0, "msg" => "添加成功"]);
            } else {
                return json(["code" => 1, "msg" => "失败!err:1"]);
            }
        } else {
            $pid = $request->param("pid");
            $this->assign("pid", $pid);
            return $this->fetch();
        }
    }

    public function menuUpd(Request $request, SysMenuModel $sysMenuModel)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            $menu_id = $data["menu_id"];
            $updResult = $sysMenuModel->updMenuData($data, $menu_id);
            if ($updResult != false) {
                return json(["code" => 0, "msg" => "修改成功"]);
            } else {
                return json(["code" => 1, "msg" => "失败!err:1"]);
            }
        } else {
            $menu_id = $request->param("menu_id");
            $pid = $request->param("pid");
            $menu = $sysMenuModel->getMenuById($menu_id);
            $this->assign([
                "menu_id" => $menu_id,
                "pid" => $pid,
                "menu" => $menu
            ]);
            return $this->fetch();
        }
    }

    public function menuDel(Request $request, SysMenuModel $sysMenuModel)
    {
        $menu_id = $request->param("menu_id");
        if (!empty($menu_id)) {
            $menu = $sysMenuModel->where(["pid" => $menu_id])->find();
            if ($menu == null) {
                $delResult = $sysMenuModel->delMenu($menu_id);
                if ($delResult != false) {
                    return json(["code" => 0, "msg" => "删除成功"]);
                } else {
                    return json(["code" => 1, "msg" => "失败!err:1"]);
                }
            } else {
                return json(["code" => 2, "msg" => "此菜单下，有子菜单，不能删除!"]);
            }
        }
    }
}
